# This plugin base on WikiInclude macro By Vegard Eriksen zyp at jvnv dot net.
# See: http://projects.edgewall.com/trac/wiki/MacroBazaar#WikiInclude
# Author: yu-ji


from trac.core import *
from trac.wiki.macros import WikiMacroBase
from trac.wiki.formatter import format_to_html, format_to_oneliner
from trac.wiki.model import WikiPage
from trac.mimeview.api import Context
from trac.resource import Resource

__all__ = ['WikiIncludeMacro', 'VariableReplaceMacro']

def variable_replace(text, req):
    text = text.replace('$AUTHNAME', req.authname)
    text = text.replace('$PAGENAME', req.args.get('page', 'WikiStart'))
    return text
   

class VariableReplaceMacro(WikiMacroBase):
    def expand_macro(self, formatter, name, args=''):
        text = variable_replace(args, formatter.req)
        return format_to_html(self.env, formatter.context, text)
        
class VariableReplaceInlineMacro(WikiMacroBase):
    def expand_macro(self, formatter, name, args=''):
        text = variable_replace(args, formatter.req)
        return format_to_oneliner(self.env, formatter.context, text)

class WikiIncludeMacro(WikiMacroBase):
    """
    Inserts the contents of another wiki page. It expands arguments in the page in the form {{N}}.
    
    Example:
    {{{
    [[WikiInclude(Foo)]]
    [[WikiInclude(Foo, Argument1, Argument2, ArgumentN)]]
    }}}
    
    Also, some variables can be used in the Page name:
     * $AUTHNAME: The name of the user currently logged in
     * ...
    """
    
    def process_text(self, args, req):
        args = [x.strip() for x in args.split(',')]
        
        name = variable_replace(args[0], req)
        page = WikiPage(self.env, name)
        
        if page.version == 0:
            text = "Wiki page not found: !%s" % name
        else:
            text = page.text
        
        i = 1
        for arg in args[1:]:
            text = text.replace('{{%d}}' % i, arg)
            i += 1
        
        return text
            
    def expand_macro(self, formatter, name, args=''):
        text = self.process_text(args, formatter.req)
        return format_to_html(self.env, formatter.context, text)

class WikiIncludeInlineMacro(WikiIncludeMacro):
    def expand_macro(self, formatter, name, args=''):
        text = self.process_text(args, formatter.req)
        return format_to_oneliner(self.env, formatter.context, text)